const Vue = require('vue')
const express = require('express')
const fs = require('fs')
const { createBundleRenderer } = require('vue-server-renderer')
const setupDevServer = require('./build/setup-dev-server')

const server = express()

server.use('/dist', express.static('./dist'))

let renderer
let onReady
const isProd = process.env.NODE_ENV === 'production'
if (isProd) {
  const serverBundle = require('./dist/vue-ssr-server-bundle.json')
  const template = fs.readFileSync('./index.template.html', 'utf-8')
  const clientManifest = require('./dist/vue-ssr-client-manifest.json')
  renderer = createBundleRenderer(serverBundle, {
    runInNewContext: false,
    template,
    clientManifest,
  })
} else {
  // 开发模式 => 监视打包构建 => 重新生成Renderer渲染器
  onReady = setupDevServer(server, (serverBundle, template, clientManifest) => {
    renderer = createBundleRenderer(serverBundle, {
      runInNewContext: false,
      template,
      clientManifest,
    })
  })
}

const render = async (req, res) => {
  try {
    const html = await renderer.renderToString({
      title: 'vue ssr',
      meta: `
        <meta name="description" content="vue ssr">
      `,
      url: req.url
    })
    res.setHeader('Content-type', 'text/html; charset=utf8') // 设置响应编码utf8
    res.end(html)
  } catch (error) {
    res.status(500).end('Internal Server Error')
  }
  
}

server.get('*', isProd ? render : async (req, res) => {
  await onReady
  render(req, res)
})

server.listen(3000, () => {
  console.log('server running at port 3000')
})
